<?php
/**
 * Created by PhpStorm.
 * User: liJia
 * Date: 2020/4/14
 * Time: 16:56
 */

namespace app\admin\business;

use app\admin\controller\Common;
use app\admin\model\User as UserModel;
use app\admin\model\User;
use app\admin\model\UserMoneylog;
use think\Exception;
use think\facade\Db;

class UserBus extends Common
{
    public $Model;
    public function __construct()
    {
        parent::__construct();
        $this->Model = new User();
    }


    /**
     * 获取用户信息列表
     * @param $where
     * @param $sort_by
     * @param $sort_order
     * @param int $pageSize
     * @param int $page
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList($where,$sort_by,$sort_order,$pageSize = 20,$page = 1){
        $result = Db::name('user')
            ->alias('a')
            ->withoutField('password')
            ->where($where)
            ->order($sort_by . ' ' . $sort_order)
            ->paginate(array('list_rows' => $pageSize, 'page' => $page))
            ->toArray();
        return $result;
    }

    /**
     * 获取下级用户ids
     * @param $user_id
     * @return string
     * @throws Exception
     */
    public static function getNextUserIds($user_id){
        try{
            // 直属下级总数
            $underlingCount = Db::name('user')->where('pid',$user_id)->count();
            // 当前用户层级
            $lvl =  Db::name('user')->where('user_id',$user_id)->value('lvl');
            $lvl = $lvl + 7;
            // 如果直属下级满六人则包括直属下级在内算起，往后6个级都是我的分销团队成员，否则只算直属下级
            if ($underlingCount > 5){ // 此处应大于5
                $userArr =  Db::name('user')
                    ->field('user_id,pid')
                    ->order('user_id','asc')
                    ->whereFindInSet('tree', $user_id)
                    ->where('lvl','<',$lvl)
                    ->select()->toArray();
            }else{
                $userArr =  Db::name('user')
                    ->field('user_id')
                    ->where('pid',$user_id)
                    ->select()->toArray();
            }
            $str = '';
            foreach ($userArr as $k => $v){
                $str .= $v['user_id'].',';
            }
            $str = rtrim($str,',');
            return $str;
        }catch (\Exception $e){
            throw new Exception($e->getMessage());
        }
    }

    public static function addCheck($data){
        $mobile = Db::name('user')->where('mobile',$data['mobile'])->find();
        if ($mobile){
            throw new \think\Exception("该手机号码已存在",1010);
        }
        $username = Db::name('user')->where('username',$data['username'])->find();
        if ($username){
            throw new \think\Exception("该用户名已存在",1010);
        }
        $shop_number = Db::name('user')->where('shop_number',$data['shop_number'])->find();
        if ($shop_number){
            throw new \think\Exception("该店铺编号已存在",1010);
        }
    }

    public static function eidtCheck($data,$user_id){
        $mobile = Db::name('user')->whereNotIn('user_id',$user_id)->where('mobile',$data['mobile'])->fetchSql(true)->find();
        if ($mobile){
            throw new \think\Exception("该手机号码已存在",1010);
        }
        $username = Db::name('user')->whereNotIn('user_id',$user_id)->where('username',$data['username'])->find();
        if ($username){
            throw new \think\Exception("该用户名已存在",1010);
        }
        $shop_number = Db::name('user')->whereNotIn('user_id',$user_id)->where('shop_number',$data['shop_number'])->find();
        if ($shop_number){
            throw new \think\Exception("该店铺编号已存在",1010);
        }
    }

    /**
     * 查询登录日志
     * @param $u_id
     * @param $where
     * @param $sort_by
     * @param $sort_order
     * @param int $pageSize
     * @param int $page
     * @return array
     * @throws \think\db\exception\DbException
     */
    public static function getLoginList($u_id,$where,$sort_by,$sort_order,$pageSize = 20,$page = 1){
        $result = Db::name('user_loginlog')->alias('a')
            ->join(['zhimeng_user'=>'d'],'d.user_id=a.user_id','left')
            ->field('a.*,d.username,d.mobile')
            ->where($where)
            ->where('a.user_id',$u_id)
            ->order($sort_by . ' ' . $sort_order)
            ->paginate(array('list_rows' => $pageSize, 'page' => $page))
            ->toArray();
        return $result;
    }



    /**
     * 统计
     */
    public static function getUserStat($where = []){
        $data = [];
        $data['user_count'] = Db::name('user')->count();
        $data['today_count'] = Db::name('user')->whereTime('create_time','today')->count();
        return $data;
    }


    public static function getLoginStat($user_id){
        $data = [];
        $data['count'] = Db::name('user_loginlog')->where('user_id',$user_id)->count();
        $data['today_count'] = Db::name('user_loginlog')->where('user_id',$user_id)->whereTime('login_time', 'today')->count();
        $data['week_count'] = Db::name('user_loginlog')->where('user_id',$user_id)->whereTime('login_time', 'week')->count();
        $data['month_count'] = Db::name('user_loginlog')->where('user_id',$user_id)->whereTime('login_time', 'month')->count();
        return $data;
    }



    /**
     * 修改用户余额
     * @param $data
     * @param $money 用户现在余额
     * @param $before_money
     * @return bool
     */
    public static function editUserMoney($data,$money,$before_money){
        // 启动事务
        Db::startTrans();
        try {
            $UserModel= new UserModel();
            $userData = [
                'money' => $money
            ];
            $UserModel->updateByUserId($data['user_id'],$userData);
            $moneyLogData = [
                'user_id' => $data['user_id'],
                'money' => $data['money'],
                'type' => $data['type'],
                'remark' => $data['remark'],
                'form' => 9, // 9为后台管理员新增
                'before_money' => $before_money,
                'after_money' => $money,
                'create_time' => time()
            ];
            $userMoneyLog = new UserMoneylog();
            $userMoneyLog->save($moneyLogData);
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
    }

}